<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>商品分类</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-row>
                <el-col>
                    <el-button type="primary" @click="showAddDialog('addFormRef')">添加分类</el-button>
                </el-col>
            </el-row>
            <tree-table :data="cateList"
                        :columns="columns"
                        :selection-type="false"
                        :expand-type="false"
                        show-index
                        index-text="#"
                        border
            >
                <template slot="isok" slot-scope="scope">
                    <i class="el-icon-success" style="color: lightgreen" v-if="scope.row.cat_deleted === false"></i>
                    <i class="el-icon-error" style="color: red" v-else></i>
                </template>
                <template slot="order" slot-scope="scope">
                    <el-tag type="primary" v-if="scope.row.cat_level === 0">一级</el-tag>
                    <el-tag type="success" v-else-if="scope.row.cat_level === 1">二级</el-tag>
                    <el-tag type="danger" v-else>三级</el-tag>
                </template>
                <template slot-scope="scope" slot="opt">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.cat_id)">
                        编辑
                    </el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id)">
                        删除
                    </el-button>
                </template>

            </tree-table>
            <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="queryInfo.pageNum"
                    :page-sizes="[1,2,3,4,5]"
                    :page-size="queryInfo.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </el-card>
        <el-dialog
                title="添加分类"
                :visible.sync="addDialogVisible"
                width="50%"
        >
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
                <el-form-item prop="cat_name" label="分类名称">
                    <el-input v-model="addForm.cat_name"></el-input>
                </el-form-item>
                <el-form-item label="父级分类">
                    <el-cascader
                            v-model="selectedKeys"
                            :options="parentCateList"
                            :props="cateProps"
                            change-on-select
                            clearable
                            @change="parentCateChange"
                    ></el-cascader>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addCate('addFormRef')">确 定</el-button>
            </span>
        </el-dialog>
        <el-dialog
                title="修改分类"
                :visible.sync="editDialogVisible"
                width="50%"
        >
            <el-form :model="editForm" :rules="editFormRules" ref="editFormRef">
                <el-form-item label="分类名称" prop="cat_name">
                    <el-input v-model="editForm.cat_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="edit('editFormRef')">确 定</el-button>
  </span>
        </el-dialog>


    </div>
</template>

<script>
  import Vue from 'vue';
  import TreeTable from "vue-table-with-tree-grid";
  Vue.component('tree-table', TreeTable);
  export default {
    name: "Cate",
    data() {
      return {
        cateList: [],
        queryInfo: {
          type: 3,
          pageSize: 5,
          pageNum: 1
        },
        total: 0,
        columns: [
          {
            align: 'center',
            headerAlign: 'center',
            label: '分类名称',
            prop: 'cat_name'
          },
          {
            align: 'center',
            headerAlign: 'center',
            label: '是否有效',
            type: 'template',
            template: 'isok'
          },
          {
            align: 'center',
            headerAlign: 'center',
            label: '排序',
            type: 'template',
            template: 'order'
          },
          {
            align: 'center',
            headerAlign: 'center',
            label: '操作',
            type: 'template',
            template: 'opt'
          }
        ],
        addDialogVisible: false,
        addFormRules: {
          cat_name: [
            {required: true, message: '请输入分类名称', trigger: 'blur'}
          ],

        },
        addForm: {
          cat_name: '',
          cat_pid: 0,
          cat_level: 0
        },
        cateProps: {
          label: 'cat_name',
          value: 'cat_id',
          children: 'children',
          expandTrigger: 'hover'
        },
        parentCateList: [],
        selectedKeys: [],
        editForm: {},
        editFormRules: {
          cat_name: [
            {required: true, message: '请输入分类名称', trigger: 'blur'}
          ]
        },
        editDialogVisible: false,
      }
    },
    created() {
      this.getCateList();
    },
    methods: {
      async getCateList() {
        const {data: res} = await this.$http({
          url: 'categories',
          method: 'get',
          params: this.queryInfo
        });
        if (res.meta.status !== 200) return this.$message.error('获取分类数据失败');
        this.cateList = res.data.result;
        this.total = res.data.total;
      },
      handleSizeChange(newSize) {
        this.queryInfo.pageSize = newSize;
        this.getCateList();
      },
      handleCurrentChange(newPage) {
        this.queryInfo.pageNum = newPage;
        this.getCateList();
      },
      showAddDialog(formName) {
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields();
        }
        this.addDialogVisible = true;
        this.getParentCateList();
        this.selectedKeys = [];
      },
      parentCateChange() {
        if (this.selectedKeys.length > 0) {
          //注意此处需要先判断数组的长度，防止数组的越界异常
          this.addForm.cat_pid = this.selectedKeys[this.selectedKeys.length - 1];
          this.addForm.cat_level = this.selectedKeys.length;
        }
      },
      async getParentCateList() {
        const {data: res} = await this.$http({
          url: 'categories',
          method: 'get',
          params: {type: 2}
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取父级分类失败');
        this.parentCateList = res.data;
      },
      addCate(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (!valid) return this.$message.error('表单不合法');
          const {data: res} = await this.$http({
            url: 'categories',
            method: 'post',
            data: this.addForm
          });
          if (res.meta.status === 403) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 201) return this.$message.error('添加分类失败');
          this.addDialogVisible = false;
          this.$message.success('添加分类成功');
          this.getCateList();

        });
      },
      async deleteCate(id) {
        const {data: res} = await this.$http({
          url: 'categories/' + id,
          method: 'delete',
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('删除分类失败');
        this.getCateList();
        this.$message.success('删除分类成功');
      },
      async showEditDialog(id) {
        const {data: res} = await this.$http({
          url: 'categories/' + id,
          method: 'get',
        });
        if (res.meta.status === 403) return this.$message.error(res.meta.msg);
        if (res.meta.status !== 200) return this.$message.error('获取分类数据失败');
        this.editForm = res.data;
        this.editDialogVisible = true;
      },
      async edit(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (!valid) return this.$message.error('表单不合法');
          const {data: res} = await this.$http({
            url: 'categories/' + this.editForm.cat_id,
            method: 'put',
            data: {cat_name: this.editForm.cat_name}
          });
          if (res.meta.status === 403) return this.$message.error(res.meta.msg);
          if (res.meta.status !== 200) return this.$message.error('修改分类失败');
          this.editDialogVisible = false;
          this.getCateList();
          this.$message.success('修改分类成功');
        });
      }

    }
  }
</script>


<style scoped>
    .el-breadcrumb {
        margin-bottom: 20px;
    }

    .zk-table {
        margin: 20px 0;
    }

    .el-cascader {
        width: 100%;
    }
</style>